//
//  WorkOrderListViewController.m
//
//  Created by Olof Millberg on 2010-03-24.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

// TODO:
// * Filtrera tilldelade och ej tilldelade

#import "WOPrototypeAppDelegate.h"
#import "WOListViewController.h"
#import "WOInfoViewController.h"
#import "WOTabBarController.h"
#import "WorkOrderCell.h"
#import "WorkOrder.h"
#import "SQLiteReader.h"
#import "WorkOrderPreview.h"

#define MAINLABEL	((UILabel *)self.navigationItem.titleView)

@implementation WOListViewController
@synthesize workOrderList;
@synthesize filteredList;
@synthesize searchBar;
@synthesize searchDC;
@synthesize tableView;
@synthesize toolBar;
@synthesize categorySelector;
@synthesize currentWorkorder;

#pragma mark Initialization Methods

- (id) init
{
	if (self = [super initWithNibName:@"WOListView" bundle:[NSBundle mainBundle]])
	{
		self.title = @"Ordrar";
	}
	return self;
}

- (void) loadView
{
	[super loadView];
	self.navigationItem.titleView = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 30.0f)] autorelease];
	[MAINLABEL setBackgroundColor:[UIColor clearColor]];
	[MAINLABEL setTextColor:[UIColor whiteColor]];
	[MAINLABEL setTextAlignment:UITextAlignmentCenter];
	[MAINLABEL setText:@"Arbetsordrar"];
	
	self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
	self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
	self.tableView.rowHeight = 64;
}

- (void)viewDidLoad
{
	[super viewDidLoad];
	
	//Fix create button
	UIBarButtonItem *createButton = [[UIBarButtonItem alloc]
									 initWithBarButtonSystemItem:(UIBarButtonSystemItem)UIBarButtonSystemItemCompose 
									 target:self
									 action:@selector(createNewWorkOrder:)];
	self.navigationItem.rightBarButtonItem = createButton;
	[createButton release];
	
	currentWorkorder = nil;
	
	// Create a search bar
	self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 64.0f, 320.0f, 44.0f)] autorelease];
	self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
	self.searchBar.keyboardType = UIKeyboardTypeAlphabet;
	self.tableView.tableHeaderView = self.searchBar;
	
	// Create the search display controller
	self.searchDC = [[[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self] autorelease];
	self.searchDC.searchResultsDataSource = self;
	self.searchDC.searchResultsDelegate = self;
	self.searchDC.delegate = self;
	
	// Create a segmented control for selecting category and add it to the toolbar.
	NSArray *categories = [NSArray arrayWithObjects:@"Mina", @"Ej tilldelade", nil]; //@"Interna", nil];
	categorySelector = [[[UISegmentedControl alloc] initWithItems:categories] autorelease];
	categorySelector.segmentedControlStyle = UISegmentedControlStyleBar;
	for (int i = 0; i < categorySelector.numberOfSegments; i++)
		[categorySelector setWidth:300/categorySelector.numberOfSegments forSegmentAtIndex:i];
	categorySelector.selectedSegmentIndex = 0;
	[categorySelector addTarget:self action:@selector(categoryChanged:) forControlEvents:UIControlEventValueChanged];
	
	UIBarButtonItem *categorySelectorItem = [[[UIBarButtonItem alloc] initWithCustomView:categorySelector] autorelease];
	UIBarButtonItem *flexibleSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
	[toolBar setItems:[NSArray arrayWithObjects:flexibleSpace, categorySelectorItem, flexibleSpace, nil]];
	
	SQLiteReader *sqlite = [[SQLiteReader alloc] initWithDatabase:@"trawoh.sql"];
	priorities = [[sqlite getPriorityTypes] retain];
	[sqlite release];
}

- (void) viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	
	if(currentWorkorder != nil)
	{
		[self updateWorkorder];
		currentWorkorder = nil;
	}
	
	//Populating the work order preview lists.
	SQLiteReader *sqlite = [[SQLiteReader alloc] initWithDatabase:@"trawoh.sql"];
	myWorkOrders = [[sqlite getAssignedWorkOrderPreviews] retain];
	[myWorkOrders sortUsingSelector:@selector(compare:)];
	unassignedWorkOrders = [[sqlite getUnassignedWorkOrderPreviews] retain];
	[unassignedWorkOrders sortUsingSelector:@selector(compare:)];
	workOrderList = (categorySelector.selectedSegmentIndex == 0) ? myWorkOrders : unassignedWorkOrders;
	[sqlite release];
	[self.tableView reloadData];
	
	//Save work order for handling termination.
	WOPrototypeAppDelegate *appDelegate = (WOPrototypeAppDelegate *)[[UIApplication sharedApplication] delegate];
	appDelegate.selectedWorkOrder = nil;
	
	//Tab bar animating.
	[self appearingAnimation];
	[UIView commitAnimations];
	
	//State saving.
	[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"currentWorkOrder"];
}

- (void) viewWillDisappear:(BOOL)animated
{	
	[super viewWillDisappear:animated];
	[self disappearingAnimation];
	[UIView commitAnimations];
}

- (void) dealloc
{
	[myWorkOrders release];
	[unassignedWorkOrders release];
	[priorities release];
	[super dealloc];
}

#pragma mark -

#pragma mark Other Methods

/* Push the view for creating a new work order */
- (void) createNewWorkOrder:(id)sender
{
	WONewWorkOrderViewController *newWOVC = [[WONewWorkOrderViewController alloc] init];
	[self.navigationController pushViewController:newWOVC animated:YES];
	[newWOVC release];
}

/* Update the current workorder */
- (void) updateWorkorder
{
	SQLiteReader *sqlite = [[SQLiteReader alloc] initWithDatabase:@"trawoh.sql"];
	[sqlite updateWorkOrder:currentWorkorder];
	[sqlite release];
}

/* Viewing assigned and unassigned work orders */
- (void) categoryChanged:(id)sender
{
	UISegmentedControl *categoryControl = sender;
	if (categoryControl.selectedSegmentIndex == 0)
		workOrderList = myWorkOrders;
	else
		workOrderList = unassignedWorkOrders;
	[self.tableView reloadData];
}

#pragma mark -

#pragma mark UISearchDisplayDelegate Methods

- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
	// For some reason these settings are reset when the user clicks the cancel button so we need to set them here.
	self.searchDC.searchResultsTableView.rowHeight = 64;
	self.searchDC.searchResultsTableView.separatorColor = [UIColor groupTableViewBackgroundColor];
	self.searchDC.searchResultsTableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
	// Update search results.
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"address.street contains[cd] %@", searchString];
	self.filteredList = [self.workOrderList filteredArrayUsingPredicate:predicate];
	
	// Yes, we want to reload the table.
	return YES;
}

#pragma mark -

#pragma mark UITableView Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView 
{ 
	// We're not using any sections.
	return 1;
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section 
{
	// Normal table
	if (aTableView == self.tableView) return self.workOrderList.count;
	
	// Search table
	return self.filteredList.count;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	// Cache stuff
	WorkOrderCell *cell = (WorkOrderCell *)[aTableView dequeueReusableCellWithIdentifier:@"WorkOrderCell"];
	if (!cell) 
	{
		cell = [[[NSBundle mainBundle] loadNibNamed:@"WorkOrderCell" owner:self options:nil] lastObject];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
	}
	
	// Are we viewing the search result table or the regular table?
	NSArray* list = (aTableView == self.tableView) ? workOrderList : filteredList;
	
	// Fetch the correct work order.
	WorkOrderPreview *workOrder = [list objectAtIndex:indexPath.row];
	
	// Set labels.
	cell.title.text = workOrder.address.street;
	cell.description.text = workOrder.description;
	
	// We use a date formatter to print the date and time on separate labels.
	NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
	[dateFormatter setDateFormat:@"EEE d MMM YYYY"];
	cell.date.text = [dateFormatter stringFromDate:workOrder.entryDate];
	[dateFormatter setDateFormat:@"HH:mm"];
	cell.time.text = [dateFormatter stringFromDate:workOrder.entryDate];
	
	// Set priority for proper background image.
	cell.priority = [priorities indexOfObject:workOrder.priority];
	
	return (UITableViewCell *) cell;
}

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{	
	//Fetch the correct work order.
	NSArray* list = (aTableView == self.tableView) ? workOrderList : filteredList;
	
	//Get the complete selected work order.
	SQLiteReader *sqlite = [[SQLiteReader alloc] initWithDatabase:@"trawoh.sql"];
	WorkOrderPreview *wop = [list objectAtIndex:indexPath.row];
	currentWorkorder = [sqlite getWorkOrderByWorkID:wop.workID];
	[sqlite release];
	
	//Save work order for handling termination.
	WOPrototypeAppDelegate *appDelegate = (WOPrototypeAppDelegate *)[[UIApplication sharedApplication] delegate];
	appDelegate.selectedWorkOrder = currentWorkorder;		
	
	//Save state.
	[[NSUserDefaults standardUserDefaults] setInteger:wop.workID forKey:@"currentWorkOrder"];
	
	// Jump to a work order detail view
	WOTabBarController* tabBarController = [[WOTabBarController alloc] initWithWorkOrder:currentWorkorder];
	[[self navigationController] pushViewController:tabBarController animated:YES];
	[tabBarController release];
}

#pragma mark -

#pragma mark Toolbar Animation Methods

/* Tab bar will appear */
- (void) appearingAnimation
{
	// Temporarily add the toolbar to the navigation controllers view.
	// Check if the last subview is a tab bar (in which case we are coming back from a work order)
	if ([[self.navigationController.view.subviews lastObject] isKindOfClass:[UITabBar class]])
		// If so, insert the toolbar behind it to make the animation look right.
		[self.navigationController.view insertSubview:self.toolBar 
											  atIndex:self.navigationController.view.subviews.count - 1];
	else
		// Otherwise just add it the normal way.
		[self.navigationController.view addSubview:self.toolBar];
	
	// Put the tab bar just below the screen«
	CGRect frame = self.toolBar.frame;
	frame.origin.y = self.toolBar.superview.frame.size.height;
	self.toolBar.frame = frame;
	
	// Begin animations
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDuration:0.4];
	
	// Move the tab bar into view
	frame = self.toolBar.frame;
	frame.origin.y -= frame.size.height;
	self.toolBar.frame = frame;
}

/* Tab bar will disappear */
- (void) disappearingAnimation
{
	// Temporarily add the toolbar to the navigation controller's view.
	[self.navigationController.view addSubview:self.toolBar];
	
	// Adjust the position of the toolbar.
	CGRect frame = self.toolBar.frame;
	frame.origin.y = self.toolBar.superview.frame.size.height - frame.size.height;
	self.toolBar.frame = frame;
	
	// Begin animations.
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDuration:0.4];
	
	// Move the toolbar out of the screen.
	frame = self.toolBar.frame;
	frame.origin.y += frame.size.height;
	self.toolBar.frame = frame;
}

/* Animation stopped so we reattach the tab bar to the tab bar controller's view */
- (void) animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
	// Reattach the toolbar.
	[self.view addSubview:self.toolBar];
	
	// Adjust the position of the toolbar.
	CGRect frame = self.toolBar.frame;
	frame.origin.y = self.toolBar.superview.frame.size.height - frame.size.height;
	self.toolBar.frame = frame;
}

#pragma mark -

@end